<template>
  <el-select placeholder="请选人" remote :loading="loading"
             class="f-single-user-selector" @change="userChange"
             :remote-method="remoteMethod" v-model="userValue"
             clearable filterable v-focus>
    <template #prefix>
      <div @click="openUserSelectModal" class="selector-button">
        <user/>
      </div>
    </template>
    <el-option v-for="opt in options" :key="opt.id"
               :label="opt.realname" :value="opt.id"/>
  </el-select>
  <UserSelectModal ref="refUserSelectModal"/>
</template>
<script setup>
import {shallowRef, unref} from 'vue';
import './style.css';
import {getAction} from '@/request/BaseRequest';
import {findListTitle, isEmpty} from '@/utils/CommonUtils';
import UserSelectModal from '@/components/SingleUserSelector/UserSelectModal.vue';

defineOptions({
  name: 'SingleUserSelector'
});
const options = shallowRef([]);
const refUserSelectModal = shallowRef();
const loading = shallowRef(false);
const emits = defineEmits(['update:modelValue', 'update:realname', 'change']);
const userValue = shallowRef(undefined);
const realnameValue = shallowRef(undefined);
const props = defineProps({
  modelValue: undefined,
  realname: undefined
})


function remoteMethod(realname) {
  if (isEmpty(realname)) {
    options.value = [];
    return;
  }
  loading.value = true;
  getAction('/plat/user/queryByRealName', {realname}).then(data => {
    loading.value = false;
    if (data.success) {
      options.value = data.result;
    }
  });
}

function userChange(value) {
  let realname = findListTitle(value, unref(options), 'realname');
  realnameValue.value = realname;

  emits('update:modelValue', value);
  emits('update:realname', realname);
}

function openUserSelectModal() {
  refUserSelectModal.value.setData();
}
</script>
